package com.qishenyuan.competition.handler;

import com.qishenyuan.competition.common.Response;
import com.qishenyuan.competition.exception.BusinessException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理 @Valid 作用于 @RequestBody 的情况
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .findFirst()
                .orElse("参数校验失败");

        return Response.failed(-1, errorMessage);
    }

    // 处理 @Valid 作用于 @RequestParam / @PathVariable 的情况
    @ExceptionHandler(ConstraintViolationException.class)
    public Response<?> handleConstraintViolationException(ConstraintViolationException ex) {
        String errorMessage = ex.getConstraintViolations().stream()
                .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
                .findFirst()
                .orElse("参数校验失败");

        return Response.failed(-1, errorMessage);
    }

    /**
     * 处理自定义业务异常 BusinessException
     */
    @ExceptionHandler(BusinessException.class)
    public Response<?> handleCommonException(BusinessException ex) {
        return Response.failed(
                ex.getErrorCode(),
                ex.getMessage()
        );
    }

}
